package com.ruoyi.quartz.controller;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.system.domain.Invite;
import com.ruoyi.system.enumutil.InviteEnum;
import com.ruoyi.system.mapper.InviteMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.service.InviteService;
import org.json.JSONObject; // 导入 JSON 库
import org.springframework.lang.UsesSunHttpServer;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.SecureRandom;
import java.util.Base64;
import java.util.Date;
import java.util.Objects;

/*
 *  @author 雨安
 *  类名： WeChatDecryptController
 *  创建时间：2025/2/14
 */

@RestController
@RequestMapping("/uni/wx/user")
public class WeChatDecryptController {
    // 微信 appId
    private static final String APP_ID = "wxbd664677f8367061";
    // 微信 AppSecret
    private static final String APP_SECRET = "b498ec52efbacda9913b7e717371a7fc";

    //用户
    @Resource
    private SysUserMapper sysUserMapper;

    //加密
    @Resource
    private PasswordEncoder passwordEncoder;

    //关系
    @Resource
    private InviteService inviteService;

    //26字母
    private static final String LETTERS = "abcdefghijklmnopqrstuvwxyz";

    //随机数字对象
    private static final SecureRandom random = new SecureRandom();

    //注册账号 或 查询账号登录
    @PostMapping("/register/user")
    public AjaxResult registerUser(String phone,Long userId,String nickName,String avatar){
        //查询数据库
        SysUser sysUser = sysUserMapper.selectUserName(phone);
        //判断是否已经有账号了
        if (Objects.nonNull(sysUser)){
            System.out.println("进入了此处直接返回");
            //直接返回当前用户
            return AjaxResult.success(sysUser);
        }
        //赋值对象
        sysUser = new SysUser();
        //判断如果为 null 则注册一个账号
        sysUser.setUserName(phone);
        sysUser.setNickName("创客");
        sysUser.setEmail("");
        sysUser.setPhonenumber(phone);
        sysUser.setSex("男");
        //头像
        sysUser.setAvatar("https://privatedomainapi.siyu99.com/LiKLKImages/log.jpg");
        //创建String拼接对象
        StringBuilder result = new StringBuilder();
        for (int i = 0; i < 6; i++) {
            //随机
            if (random.nextBoolean()) {
                //生成
                int digit = random.nextInt(10) + 1;
                //拼接
                result.append(digit);
            } else {
                //英文
                char letter = LETTERS.charAt(random.nextInt(LETTERS.length()));
                //拼接
                result.append(letter);
            }
        }
        //设置密码
        sysUser.setPassword(passwordEncoder.encode(result));
        //设置管理员可见密码
        sysUser.setAdminPassword(result.toString());
        //设置状态
        sysUser.setStatus("0");
        //设置逻辑删除
        sysUser.setDelFlag("0");
        //设置羊毛类型
        sysUser.setPickType(1);
        //设置默认值
        sysUser.setCreateBy("系统注册");
        sysUser.setCreateTime(new Date());
        sysUser.setUpdateBy("系统注册");
        sysUser.setUpdateTime(new Date());
        sysUser.setRemark("账号来自,系统注册功能。");
        //平台积分
        sysUser.setScore(BigDecimal.valueOf(0));
        //平台收益
        sysUser.setIncome(BigDecimal.valueOf(0));
        //执行添加
        sysUserMapper.insertUser(sysUser);
        System.out.println("我是新增的对象" + sysUser);
        //判断是否有邀请用户
        if (Objects.nonNull(userId) && userId != 0){
            //查询直接推荐使用人
            SysUser ztUser = sysUserMapper.selectUserById(userId);
            //判断使用人不为null
            if (Objects.nonNull(ztUser)){
                System.out.println("进入了拥有直推用户=111111122222222222333333333=======" + ztUser);
                //绑定当前用户为邀请用户的直推用户
                Invite invite = new Invite();
                //设置被邀请用户id
                invite.setInviteUserId(sysUser.getUserId());
                //设置邀请用户id
                invite.setUserId(ztUser.getUserId());
                //设置关系
                invite.setInviteType(InviteEnum.ZhiTui.getType());
                //设置默认值
                invite.setCreateBy(sysUser.getUserName());
                invite.setCreateTime(new Date());
                invite.setUpdateBy(sysUser.getUserName());
                invite.setUpdateTime(new Date());
                invite.setDeleteFlag(Boolean.FALSE);
                //执行添加
                inviteService.save(invite);
                //查询直推人是否有直推
                Invite ztInvite = inviteService.getOne(new LambdaQueryWrapper<Invite>()
                        //直推人编号
                        .eq(Invite::getInviteUserId, ztUser.getUserId())
                        //类型
                        .eq(Invite::getInviteType,InviteEnum.ZhiTui.getType())
                        //逻辑删除
                        .eq(Invite::getDeleteFlag,Boolean.FALSE)
                );
                System.out.println("我是查看是否有直推是否还存在直推查询===============================" + ztInvite);
                //判断是否还有直推
                if (Objects.nonNull(ztInvite)){
                    System.out.println(ztInvite.getUserId() + "=========saaaaaaaaaaaaaaaaaaaaaaa================================================================进入了间推分配" + sysUser.getUserId());
                    //绑定当前用户为邀请用户的直推用户
                    Invite jtInvite = new Invite();
                    //设置被邀请用户id
                    jtInvite.setInviteUserId(sysUser.getUserId());
                    //设置邀请用户id
//                    jtInvite.setUserId(ztInvite.getUserId());
                    jtInvite.setUserId(ztInvite.getUserId());
                    //设置关系
                    jtInvite.setInviteType(InviteEnum.JianTui.getType());
                    //设置默认值
                    jtInvite.setCreateBy(sysUser.getUserName());
                    jtInvite.setCreateTime(new Date());
                    jtInvite.setUpdateBy(sysUser.getUserName());
                    jtInvite.setUpdateTime(new Date());
                    jtInvite.setDeleteFlag(Boolean.FALSE);
                    //执行添加
                    inviteService.save(jtInvite);
                }
            }
        }

        //返回结果
        return AjaxResult.success(sysUser);
    }

    //获取用户手机号
    @PostMapping("/get/user/phone")
    public AjaxResult getUserPhone(String code) throws Exception {
        //获取token
        String accessToken = getAccessToken();
        //获取手机号
        String phoneNumberInfo = getUserPhoneNumber(accessToken, code);
        System.out.println("Phone Number Info: " + phoneNumberInfo);
        //返回结果
        return AjaxResult.success(phoneNumberInfo);
    }

    //获取电话号码
    public static String getUserPhoneNumber(String accessToken, String code) {
        String url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + accessToken;
        String jsonInputString = "{\"code\": \"" + code + "\"}"; // 构建请求体
        try {
            // 创建 HTTP 连接
            HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setDoOutput(true);
            // 发送请求
            try (OutputStream os = connection.getOutputStream()) {
                byte[] input = jsonInputString.getBytes("utf-8");
                os.write(input, 0, input.length);
            }
            // 获取响应
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) { // 检查响应是否成功
                BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                StringBuilder response = new StringBuilder();
                String inputLine;
                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();
                // 解析响应体
                com.alibaba.fastjson2.JSONObject jsonObject = com.alibaba.fastjson2.JSONObject.parseObject(response.toString());
                // 检查返回的错误码
                if (jsonObject.getInteger("errcode") == 0) {
                    // 提取 phone_info 对象
                    com.alibaba.fastjson2.JSONObject phoneInfo = jsonObject.getJSONObject("phone_info");
                    System.out.println(phoneInfo + "我是测试查看获取的数据内容");
                    // 获取 phoneNumber
                    return phoneInfo.getString("phoneNumber");
                }
            } else {
                System.out.println("Error: Unable to get phone number. Response Code: " + responseCode);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    //获取session key
    public static String getSessionKey(String code) {
        String sessionKey = "";
        String url = "https://api.weixin.qq.com/sns/jscode2session";
        String appId = APP_ID; // 替换为您的 AppID
        String appSecret = APP_SECRET; // 替换为您的 AppSecret
        try {
            // 构建请求 URL
            String requestUrl = String.format("%s?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code",
                    url, appId, appSecret, "532152189d33f63b8c0fae76ab156fb48f85c1fbfb54fc8a31095d7b2a21d826");
            // 发送 GET 请求
            HttpURLConnection connection = (HttpURLConnection) new URL(requestUrl).openConnection();
            connection.setRequestMethod("GET");
            // 获取响应
            int responseCode = connection.getResponseCode();
            if (responseCode != HttpURLConnection.HTTP_OK) {
                System.out.println("Request failed with response code: " + responseCode);
                return null;
            }
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String inputLine;
            StringBuilder response = new StringBuilder();
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();
            // 打印响应内容
            System.out.println("Response: " + response.toString());
            // 解析 JSON 响应
            com.alibaba.fastjson2.JSONObject jsonObject = JSON.parseObject(response.toString());
            if (jsonObject.containsKey("errcode")) {
                System.out.println("Error code: " + jsonObject.getString("errcode"));
                System.out.println("Error message: " + jsonObject.getString("errmsg"));
                return null;
            }
            sessionKey = jsonObject.getString("session_key");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sessionKey;
    }

    //获取token
    public static String getAccessToken() throws Exception {
        String urlString = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + APP_ID + "&secret=" + APP_SECRET;
        URL url = new URL(urlString);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        // 读取响应
        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String inputLine;
        StringBuilder response = new StringBuilder();
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
        // 打印返回的完整响应
        System.out.println("Response: " + response.toString());
        // 解析 JSON，提取 access_token
        JSONObject jsonResponse = new JSONObject(response.toString());
        String accessToken = jsonResponse.getString("access_token");
        // 返回 access_token
        return accessToken;
    }


}
